package com.bz.xtcx.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bz.xtcx.manager.comom.XtcxException;
import com.bz.xtcx.manager.entity.*;
import com.bz.xtcx.manager.mapper.BusUserCheckMapper;
import com.bz.xtcx.manager.mapper.CmsCategoryMapper;
import com.bz.xtcx.manager.mapper.CmsContentMapper;
import com.bz.xtcx.manager.mapper.CmsFileMapper;
import com.bz.xtcx.manager.service.ICmsCategoryService;
import com.bz.xtcx.manager.vo.VoQueryCms;
import com.bz.xtcx.manager.vo.VoResponse;
import com.bz.xtcx.manager.vo.VoTaskSum;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class CmsCategoryService extends BaseService implements ICmsCategoryService {
	
	@Autowired
	private CmsCategoryMapper cmsCategoryMapper;
	
	@Autowired
	private CmsContentMapper cmsContentMapper;
	
	@Autowired
	private BusUserCheckMapper busUserCheckMapper;
	
	@Autowired
	private CmsFileMapper cmsFileMapper;

	@Override
	public List<CmsCategory> getTreeByCondition(VoQueryCms query) {
		List<CmsCategory> listAll = cmsCategoryMapper.findByCondition(query);
		List<CmsCategory> listPar = new ArrayList<CmsCategory>();
		
		if(listAll != null && listAll.size() > 0) {
			
			for(CmsCategory cate : listAll) {
				if(StringUtils.isEmpty(cate.getParentId())) {//父目录顺序
					cate.setLevel(1);
					setTreeSub(cate, listAll);
					listPar.add(cate);
				}
			}
			
		}
		return listPar;
	}
	
	void setTreeSub(CmsCategory par, List<CmsCategory> listAll) {
		
		for(CmsCategory cate : listAll) {
			if(StringUtils.isEmpty(cate.getParentId())) {//父目录
				continue;
				
			} else if(cate.getParentId().equals(par.getId())) {//子目录
				if(par.getChildren() == null) {
					par.setChildren(new ArrayList<CmsCategory>());
				}
				cate.setLevel(par.getLevel() + 1);
				par.getChildren().add(cate);
				setTreeSub(cate, listAll);
			} 
		}
	}
	
	void setTreeSub2(CmsCategory par, List<CmsCategory> listAll) {
		//Iterator<CmsCategory> it = listAll.iterator();
		for (Iterator<CmsCategory> iter = listAll.iterator(); iter.hasNext();) {
			CmsCategory cate = iter.next();
			if(StringUtils.isEmpty(cate.getParentId())) {//父目录
				continue;
				
			} else if(cate.getParentId().equals(par.getId())) {//子目录
				if(par.getChildren() == null) {
					par.setChildren(new ArrayList<CmsCategory>());
				}
				cate.setLevel(par.getLevel() + 1);
				par.getChildren().add(cate);
				setTreeSub(cate, listAll);
			} 
		}
		
	}
	
	public static void main(String[] args) {
		List<String> list = null;
		//list.add("1");
		String s = "[{\r\n" + 
				"          \"name\": \"food.jpeg\",\r\n" + 
				" \r\n" + 
				"          \"url\": \"http://106.14.172.38:8990/jmrhupload\" \r\n" + 
				"   \r\n" + 
				"        }]";
		System.out.println(s);
		JSONArray json = JSON.parseArray(s);
		System.out.println(json);
		Map<String,String> map = null;
		//System.out.println(map.isEmpty());
		map = new HashMap<String,String>();
		System.out.println(map.isEmpty());
		
	}

	@Override
	public VoResponse add(CmsCategory e) {
		VoResponse voRes = new VoResponse();
		User user = this.getUser();
		e.setReadable(1);//可见
		e.setCreater(user.getUserName());
		e.setUpdater(user.getUserName());
		if(StringUtils.isEmpty(e.getParentId())) {//add父目录
			if(cmsCategoryMapper.findParByName(e.getName()) != null) {
				voRes.setFail(voRes);
				voRes.setMessage("目录名称已存在");
				return voRes;
			}
		}else {//add 子目录
			if(cmsCategoryMapper.findById(e.getParentId()) == null) {
				voRes.setFail(voRes);
				voRes.setMessage("parentId 不存在");
				return voRes;
			}
			if(cmsCategoryMapper.findByParentIdAndName(e.getParentId(), e.getName()) != null) {
				voRes.setFail(voRes);
				voRes.setMessage("目录名称已存在2");
				return voRes;
			}
		}
		if(cmsCategoryMapper.findByCode(e.getCode()) != null ) {
			voRes.setFail(voRes);
			voRes.setMessage("目录编码已存在");
			return voRes;
		}
		this.setIcon(e);
		if(cmsCategoryMapper.insert(e) == 0) {
			voRes.setFail(voRes);
			voRes.setMessage("添加数据异常");
			return voRes;
		}
		return voRes;
	}
	
	
	void setIcon(CmsCategory e) {
		if(e.getIcons() == null || e.getIcons().size() == 0) {
			return;
		}
		e.setIcon(e.getIcons().get(0).get("url"));
	}
	
	
	@Override
	public VoResponse update(CmsCategory e) {
		VoResponse voRes = new VoResponse();
		User user = this.getUser();
		CmsCategory old = cmsCategoryMapper.findById(e.getId());
		old.setUpdater(user.getUserName());
		if(!old.getName().equals(e.getName())) {
			if(StringUtils.isEmpty(old.getParentId())) {//update父目录名称
				if(cmsCategoryMapper.findParByName(e.getName()) != null) {
					voRes.setFail(voRes);
					voRes.setMessage("目录名称已存在");
					return voRes;
				}
			}else {//update子目录名称
				if(cmsCategoryMapper.findByParentIdAndName(old.getParentId(), e.getName()) != null) {
					voRes.setFail(voRes);
					voRes.setMessage("目录名称已存在2");
					return voRes;
				}
			}
			old.setName(e.getName());
		}
		if(!old.getCode().equals(e.getCode())) {
			if(cmsCategoryMapper.findByCode(e.getCode()) != null ) {
				voRes.setFail(voRes);
				voRes.setMessage("目录编码已存在");
				return voRes;
			}
			old.setCode(e.getCode());
		}
		old.setTypeId(e.getTypeId());
		old.setIcon(e.getIcon());
		old.setOnlyUrl(e.getOnlyUrl());
		old.setContentUrl(e.getContentUrl());
		old.setTags(e.getTags());
		old.setSort(e.getSort());
		old.setReadable(e.getReadable());
		old.setMemo(e.getMemo());
		old.setIcons(e.getIcons());
		this.setIcon(old);
		if(cmsCategoryMapper.update(old) == 0) {
			voRes.setFail(voRes);
			voRes.setMessage("添加数据异常");
			return voRes; 
		}
		return voRes;
	}
	
	@Override
	public boolean del(String id) {
		CmsCategory e = cmsCategoryMapper.findById(id);
		if(e == null) {
			return false;
		}
		if(cmsCategoryMapper.findByParentId(e.getId()).size() > 0) {
			return false;
		}
		if(cmsCategoryMapper.del(id) == 0) {
			return false;
		}
		return true;
	}
	
	@Override
	public CmsCategory getCategoryById(String id) {
		CmsCategory category = cmsCategoryMapper.findById(id);
		return category;
	}
	
	@Override
	public List<CmsCategory> getSubCategorys(){
		List<CmsCategory> list = cmsCategoryMapper.findLeafNodes();
		for (int i = list.size() - 1; i >= 0; i--) {
		    if ("HDTZ".equals(list.get(i).getCode())
                    || "JMRHZN".equals(list.get(i).getCode())
                    || "GYWM".equals(list.get(i).getCode())
                    || "FWZXJS".equals(list.get(i).getCode())
                    || "PTJS".equals(list.get(i).getCode())
                    || "JDZPTJS".equals(list.get(i).getCode())
                    || "HDTZ".equals(list.get(i).getCode())
                    || "LXWM".equals(list.get(i).getCode())
                    || "XMGL".equals(list.get(i).getCode())
                    || "XTCX".equals(list.get(i).getCode())
                    || "JMRH".equals(list.get(i).getCode())) {
                list.remove(i);
            }
        }
		return list;
	}
	
	@Override
	public boolean onOrOffCategory(String id, int val) {
		CmsCategory e = cmsCategoryMapper.findById(id);
		if(e !=null && e.getReadable() != val) {
			if(cmsCategoryMapper.updateStatus(val, id) > 0) {
				return true;
			}
		}
		return false;
	}

	@Override
	public VoResponse addOrUpdate(CmsContent e) {
		VoResponse voRes = new VoResponse();
		Date now = new Date();
		User user = this.getUser();
		if(e.getPublishNow() == 0) {//立刻发布
			e.setPublishDate(now);
		}else if(e.getPublishDate() == null){
			voRes.setFail(voRes);
			voRes.setMessage("定时发布时发布时间必选");
			return voRes;
		}
		if(e.getId() == null) {
			e.setCreater(user.getUserName());
			e.setClicks(0);
			e.setReadable(1);
			e.setPublishUserId(user.getUserId());
		}else {
			CmsContent old = cmsContentMapper.findById(e.getId());
			if(old == null) {
				voRes.setFail(voRes);
				voRes.setMessage("数据异常");
				return voRes;
			}
			if(old.getCheckStatus() == 0) {
				voRes.setFail(voRes);
				voRes.setMessage("待审核状态下不能再更新");
				return voRes;
			}
		}
		if(e.getCheckStatus() == 1) {
			e.setCheckUserId(user.getUserId());
			e.setCheckDate(now);
		}
		e.setUpdater(user.getUserName());
		this.setCover(e);
		if(!this.saveOrUpdate(e)) {
			voRes.setFail(voRes);
			voRes.setMessage("保存失败");
		}else {
			List<CmsFile> files = e.getCmsFileList();
			if(files != null && files.size() > 0) {
				for(CmsFile file : files) {
					if(StringUtils.isEmpty(file.getOwnerId())) {
						file.setOwnerId(e.getId());
						cmsFileMapper.updateOwnerId(file);
					}
				}
			}
				
		}
		return voRes;
	}
	
	void setCover(CmsContent e) {
		if(e.getCovers() == null || e.getCovers().size() == 0) {
			return;
		}
		e.setCover(e.getCovers().get(0).get("url"));
	}

	public boolean saveOrUpdate(CmsContent e) {
		int result = 0;
		if(e.getId() == null) {
			result = cmsContentMapper.insert(e);
		}else {
			result = cmsContentMapper.update(e);
		}
		if(result > 0) {
			return true;
		}
		return false;
	}

	@Override
	public boolean delContent(String id) {
		CmsContent e = cmsContentMapper.findById(id);
		if(e != null ) {
			if(cmsContentMapper.del(id) > 0) {
				return true;
			}
		}
		return false;
	}

	@Override
	public PageInfo<CmsContent> getPageByCondition(VoQueryCms query, int pageNum, int pageSize, String orderBy) throws XtcxException {
		User u = getUser();
		if (null == u) {
			throw new XtcxException("登录已超时，请重新登录");
		}
		Page<CmsContent> page = PageHelper.startPage(pageNum, pageSize);
		if(StringUtils.isEmpty(orderBy)) {
			PageHelper.orderBy("a.create_time desc");
		}else {
			PageHelper.orderBy(orderBy);
		}
        if (0 != u.getUserType() && 101 != u.getUserType()) {
            query.setPublishUserId(u.getUserId());
        }
		cmsContentMapper.findByCondition(query);
		PageInfo<CmsContent> info = new PageInfo<CmsContent>(page);
		return info;
	}

	@Override
	public CmsContent getContentById(String id) {
		CmsContent content = cmsContentMapper.findById(id);
		return content;
	}

	@Override
	public boolean check(String id) {
		CmsContent e = cmsContentMapper.findById(id);
		if(e == null || e.getCheckStatus() != 0) {
			return false;
		}
		e.setCheckStatus(1);
		User user = this.getUser();
		e.setCheckUserId(user.getUserId());
		e.setCheckDate(new Date());
		if(cmsContentMapper.updateCheckStatus(e) > 0) {
			return true;
		}
		return false;
	}

	@Override
	public VoResponse check(List<String> ids) {
		VoResponse voRes = new VoResponse();
		int count = 1;
		for(String id : ids) {
			if(!this.check(id)) {
				voRes.setFail(voRes);
				voRes.setMessage("第" + count + "条数据审核失败；");
				return voRes;
			}
			count ++;
		}
		return voRes;
	}

	@Override
	public VoResponse reject(String id, String info) {
		VoResponse voRes = new VoResponse();
		CmsContent e = cmsContentMapper.findById(id);
		if(e == null) {
			voRes.setNull(voRes);
			voRes.setMessage("数据异常");
			return voRes;
		}
		if(e.getCheckStatus() != 0) {
			voRes.setFail(voRes);
			voRes.setMessage("状态异常");
			return voRes;
		}
		User user = this.getUser();
		BusUserCheck m = new BusUserCheck();
		m.setCheckStatus(2);
		m.setChecker(user.getUserName());
		m.setInfo(info);
		m.setFormId(id);
		int result = busUserCheckMapper.insert(m);
		if(result > 0) {
			e.setCheckStatus(2);
			e.setCheckUserId(user.getUserId());
			e.setCheckDate(new Date());
			result = cmsContentMapper.updateCheckStatus(e);
			if(result > 0) {
				return voRes;
			}
		}
		voRes.setFail(voRes);
		return voRes;
	}

	@Override
	public VoResponse onOrOff(String id, int val) {
		VoResponse voRes = new VoResponse();
		if(val == 0 || val == 1) {
			cmsContentMapper.updateStatus(val, id);
		}
		return voRes;
	}

	@Override
	public VoResponse isTop(String id, int val) {
		VoResponse voRes = new VoResponse();
		if(val >= 0) {
			cmsContentMapper.updateStickSort(val, id);
		}
		return voRes;
	}

	@Override
	public VoResponse myTaskDoingSum() {
	    VoResponse voRes = new VoResponse();
		User user = this.getUser();
        if (null == user) {
            voRes.setFail(voRes);
            voRes.setMessage("登录已超时，请重新登录");
            return voRes;
        }
        if (0 == user.getUserType() || 101 == user.getUserType()) {
            voRes.setData(cmsContentMapper.findAllSubmitSum());
        } else {
            voRes.setData(cmsContentMapper.findMySubmitSum(user.getUserId()));
        }
		return voRes;
	}
	
}
